package com.xkcoding.helloworld.strategy.mapFunctional;

import com.xkcoding.helloworld.strategy.enumWay.DiscountEnum;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class QueryGrantTypeService {

    private Map<DiscountEnum, Function<BigDecimal,String>> grantTypeMap=new HashMap<>();

    /**
     *  初始化业务分派逻辑,代替了if-else部分
     *  key: 优惠券类型
     *  value: lambda表达式,最终会获得该优惠券的发放方式
     */
    @PostConstruct
    public void dispatcherInit(){
        grantTypeMap.put(DiscountEnum.strategyA, price->this.discountA(price));
        grantTypeMap.put(DiscountEnum.strategyB, price->this.discountB(price));
        grantTypeMap.put(DiscountEnum.strategyC, price->this.discountC(price));
    }

    public String getResult(DiscountEnum strategyType, BigDecimal price){
        //Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
        Function<BigDecimal,String> result=grantTypeMap.get(strategyType);
        if(result!=null){
         //传入resourceId 执行这段表达式获得String型的grantType
            return result.apply(price);
        }
        return "查询不到该优惠券的发放方式";
    }

    private String discountA(BigDecimal price){
        return "执行折扣A优惠后金额："+price.multiply(new BigDecimal("0.9"));
    }
    private String discountB(BigDecimal price){
        return "执行折扣B优惠后金额："+price.multiply(new BigDecimal("0.75"));
    }
    private String discountC(BigDecimal price){
        return "执行折扣C优惠后金额："+price.multiply(new BigDecimal("0.6"));
    }
}





